import { useState, useCallback, useRef, useEffect } from 'react'
import { connect } from 'react-redux'
import { useTranslation } from 'react-i18next'
import { Card, Box, LinearProgress, Typography, IconButton, Grid } from '@mui/material';
import DeleteIcon from '@mui/icons-material/Delete';
import { DragDrop } from '@uppy/react'
import Uppy from '@uppy/core'
import XHRUpload from '@uppy/xhr-upload'
import message from '@/utils/system/message'
import '@uppy/core/dist/style.css'
import '@uppy/drag-drop/dist/style.css'
// import SingleFileUpload from './SingleFileUpload';

const FileItem = (props) => {
  const { name, id } = props
  const deleteFile = useCallback(() => {
    props.deleteFile(id)
  }, [props.deleteFile])
  return (
    <Grid item xs={4} style={{ height: 50, padding: 0 }}>
      <Card style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', width: '100%', height: '100%', padding: '0.3rem 0.4rem' }}>
        <Typography noWrap>{name}</Typography>
        <IconButton onClick={() => deleteFile()} style={{ padding: 0 }}>
          <DeleteIcon></DeleteIcon>
        </IconButton>
      </Card>
    </Grid>
  )
}

/**
 * 
 * @param {*} props 
 * props.maxNumberOfFiles
 * props.minNumberOfFiles
 * props.maxFileSize
 * props.minFileSize
 * props.maxTotalFileSize
 * props.allowedFileTypes
 * props.fileAdded(file) 当文件上传成功时回传文件
 * @returns 
 */
const MyUppy = (props) => {

  const { t } = useTranslation()

  const [progress, setProgress] = useState(0)
  const [showProgress, setShowProgress] = useState(false)
  const [update, setUpdate] = useState(false)
  const fileList = useRef([])
  
  const uppy = new Uppy({
    restrictions: {
      maxNumberOfFiles: props.maxNumberOfFiles || 1,
      minNumberOfFiles: props.minNumberOfFiles || 0,
      maxFileSize: props.maxFileSize || null,
      minFileSize: props.minFileSize || null,
      maxTotalFileSize: props.maxTotalFileSize || null,
      allowedFileTypes: props.allowedFileTypes || null, // for example ['image/*', '.jpg', '.jpeg', '.png', '.gif']
    },
    autoProceed: props.autoProceed ? true : false,
    allowMultipleUploadBatches: false,
    onBeforeFileAdded: (currentFile) => {
      if (showProgress) {
        message.warning({content: t('common.waitUploading')})
        uppy.removeFiles([currentFile.id], 'wait upload.')
        return false
      }
      if (fileList.current.length >= (props.maxNumberOfFiles || 1)) {
        console.log('上传文件数量受限')
        message.warning({content: t('common.filesNumberMax', {number: props.maxNumberOfFiles || 1})})
        return false
      }
      if (currentFile && Object.keys(currentFile).length) {
        const index = fileList.current.findIndex(item => {
          return item.id === currentFile.id
        })
        if (index >= 0) {
          console.log('不可上传同样的文件')
          message.warning({content: t('common.fileExist')})
          return false
        }
      }
      if (props.beforeAddFile && typeof (props.beforeAddFile) === 'function') {
        if (!props.beforeAddFile(currentFile)) {
          return false
        }
      }
      if (props.autoProceed) {
        setShowProgress(true)
        setProgress(0)
      }
    }
  }).use(XHRUpload, {
    id: 'XHRUpload',
    endpoint: `/file-upload`,
    method: 'post',
    formData: true,
    fieldName: 'file',
    bundle: true,
    timeout: 30000 * 1000, // default 30s
    limit: 3, // Limit the amount of uploads going on at the same time.
    headers: {
      Authorization: 'Bearer ' + window.localStorage.getItem('accessToken'),
      accessKey: props.auth.appId
    }
  })

  // 上传进度监听
  uppy.on('progress', (progress) => {
    console.log(progress, 'upload progress------------')
    setProgress(progress)
  })

  uppy.on('error', (data) => {
    setShowProgress(false)
    console.log(data, 'error')
  })

  uppy.on('file-added', (file) => {
    if (props.fileAdded && typeof (props.fileAdded) === 'function') {
      props.fileAdded(file)
    }
    if (!props.autoProceed && !props.autoProceed) { // 如果是自动上传的则先不添加文件
      fileList.current = [file, ...fileList.current]
      setUpdate(!update)
    }
  })

  // 上传错误监听
  uppy.on('upload-error', (file, error, response) => {
    console.log('error with file:', file.id)
    console.log('error message:', error)
    console.log('error response:', response)
    setShowProgress(false)
  })

  // 上传成功监听
  uppy.on('complete', async (result) => {
    console.log(result, 'complete-----------')
    try {
      if (result && result.successful && result.successful.length) {
        fileList.current = [...result.successful, ...fileList.current]
      } else if (result && result.failed && result.failed.length) { // 在失败里有文件，则要处理
        message.error({ content: t('common.uploadFalse') })
        result.failed.forEach(item => {
          uppy.removeFile(item.id)
        })
      }
      setProgress(100)
      setShowProgress(false)
      setUpdate(!update)
    } catch (err) {
      setShowProgress(false)
      console.log(err)
    }
  })

  // 删除已上传的文件
  const deleteFile = useCallback((fileId) => {
    const delAfterFile = fileList.current.filter(item => {
      return item.id !== fileId
    })
    uppy.removeFile(fileId)
    // setFileList(delAfterFile)
    fileList.current = delAfterFile
    setUpdate(!update)
  }, [fileList, update])

  useEffect(() => {
    console.log(fileList.current, 'change')
  }, [fileList.current])

  return (
    <div style={{ width: '100%', height: '100%', position: 'relative' }}>
      <DragDrop
        width="100%"
        height="100%"
        note=""
        uppy={uppy}
        locale={{
          strings: {
            // Text to show on the droppable area.
            // `%{browse}` is replaced with a link that opens the system file selection dialog.
            dropHereOr: `${t('common.dropOr')} %{browse}`,
            // Used as the label for the link that opens the system file selection dialog.
            browse: `${t('common.browse')}`,
          },
        }}
      >
      </DragDrop>
      <Grid container spacing={2} style={{ marginTop: 5, marginLeft: 0 }}>
        {
          fileList.current.map(item => {
            return (
              <FileItem {...item} key={item.id} deleteFile={deleteFile}></FileItem>
            )
          })
        }
      </Grid>
      {
        showProgress && (
          <Box sx={{ width: '100%', position: 'absolute', top: 0 }}>
            <LinearProgress variant="determinate" value={progress} />
          </Box>
        )
      }
    </div>
  )
}
const mapStateToProps = state => state
export default connect(mapStateToProps)(MyUppy)